package com.cw.jeeyt.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import cn.hutool.core.codec.Base64;

@SuppressWarnings("restriction")
public class HMACSHA1Util {
    /**
     * HMAC-SHA1签名
     *
     * @param message
     * @param key
     * @return
     */
    public static String getHmacSHA1(String message, String key) {
        String hmacSha1 = null;
        try {
            // url encode
            message = URLEncoder.encode(message, "UTF-8");
            // hmac-sha1加密
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(message.getBytes());
            hmacSha1 = Base64.encode(byteHMAC);
        } catch (NoSuchAlgorithmException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return hmacSha1;
    }

    public static void main(String[] args) throws IOException {
        long time = System.currentTimeMillis();
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;//5位随即数
        String nonce = rannum + "";
        String signature = HMACSHA1Util.getHmacSHA1(time + nonce, "Abcd1234");//appKey =公共密钥
        String smsUrl = "http://localhost:8080/rest/sendMessage?appid=1000000" + "&timestamp=" + time + "&nonce="
            + nonce + "&signature=" + signature;
        System.out.println(smsUrl);

        String mySignature = HMACSHA1Util.getHmacSHA1(time + nonce, "Abcd1234");
        System.out.println(mySignature);
    }
}